<template>
  <div v-loading="loading" element-loading-background="rgba(0, 0, 0, 0.8)">
    <RemarkHouseItem :item="item"></RemarkHouseItem>
    <el-form ref="form" :model="model" label-width="100px" size="mini">
      <el-form-item label="定位打卡" required>
        <el-button
          v-if="isShowClockInBtn"
          :loading="isClockInLoading"
          type="primary"
          round
          plain
          @click="handleShowClickIn"
        >
          {{ isClockInLoading ? '自动打卡中...' : '点击选择打卡地点' }}
        </el-button>
        <i
          v-show="clockInStatus !== '0'"
          :class="[
            ['1', '3'].indexOf(clockInStatus) !== -1
              ? 'el-icon-circle-check text-green'
              : 'el-icon-circle-close text-red',
            'ml10'
          ]"
        >
          {{
            ['1', '3'].indexOf(clockInStatus) !== -1
              ? `${clockInStatus === '3' ? '自动' : ''}打卡成功 （30分钟内有效）`
              : `打卡失败 ${clockInErrorMsg ? '(' + clockInErrorMsg + ')' : ''}`
          }}
        </i>
      </el-form-item>
      <el-form-item label="带看时间" required>
        <el-date-picker
          v-model="model.reviewDate"
          type="date"
          :clearable="false"
          placeholder="选择日期"
          value-format="timestamp"
          :picker-options="pickerOptions"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="上传照片" :required="!(item && item.haveAuditSuccess)">
        <div>
          <el-upload
            ref="upload"
            :file-list="uploadList"
            action="#"
            list-type="picture-card"
            :http-request="uploadImg"
            :before-upload="handleUploadBefore"
            :multiple="true"
          >
            <i class="el-icon-plus"></i>
            <div class="full" slot="file" slot-scope="{ file }">
              <el-image class="el-upload-list__item-thumbnail" :src="file.url" fit="cover" />
              <span class="el-upload-list__item-actions">
                <span class="el-upload-list__item-preview" @click="handleUploadPreview(file)">
                  <i class="el-icon-zoom-in"></i>
                </span>
                <span class="el-upload-list__item-delete" @click="handleUploadRemove(file)">
                  <i class="el-icon-delete"></i>
                </span>
              </span>
            </div>
          </el-upload>
        </div>
        <el-button class="mt10" type="primary" @click="isShowSelectDialog = true">选择全景拍照</el-button>
        <el-button class="mt10" v-if="item.vrUrl" type="primary" size="mini" @click="handleCrawlXflVr"
          >幸福里全景拍照</el-button
        >
      </el-form-item>
      <el-form-item label="房评内容" required>
        <el-input
          type="textarea"
          placeholder="请输入房评内容"
          v-model="model.commentContent"
          show-word-limit
          minlength="30"
          maxlength="300"
          :rows="5"
          style="font-size: 14px"
        ></el-input>
        <el-button class="refresh" type="text" icon="el-icon-refresh" @click="handleRefresh"> 换一组</el-button>
      </el-form-item>
      <el-form-item class="d-flex jc-end">
        <el-button type="primary" round @click="submit">提交房评</el-button>
      </el-form-item>
    </el-form>

    <!-- 预览图片弹窗 -->
    <el-dialog :visible.sync="isShowPreviewDialog" append-to-body width="600px">
      <img style="width: 100%; height: 400px" :src="previewImageUrl" alt="" />
    </el-dialog>

    <!-- vr  选择列表弹窗 -->
    <el-dialog class="dialog-radius" append-to-body :visible.sync="isShowSelectDialog" title="选择全景" width="800px">
      <RemarkVrList v-if="isShowSelectDialog" :houseData="item" @screenshot="handleTakePhoto"></RemarkVrList>
    </el-dialog>

    <!-- 打卡弹窗 -->
    <el-dialog
      class="dialog-radius"
      :visible.sync="isShowClockIn"
      title="带看房评打卡-选位置"
      width="400px"
      :close-on-click-modal="false"
      append-to-body
    >
      <RemarkClockIn v-if="isShowClockIn" v-bind="clockInData" @remarkChange="handleRemarkChange"></RemarkClockIn>
    </el-dialog>

    <!-- vr 截图弹窗 -->
    <el-dialog
      class="dialog-radius"
      title="全景拍照"
      :visible.sync="isShowVrDialog"
      width="800px"
      append-to-body
      :close-on-click-modal="false"
    >
      <iframe v-if="isShowVrDialog" class="vr" ref="iframe" :src="vrUrl">
        <span>你的浏览器不支持该功能</span>
      </iframe>
    </el-dialog>
  </div>
</template>
<script>
import RemarkHouseItem from './RemarkHouseItem.vue';
import RemarkClockIn from './RemarkClockIn.vue';
import RemarkVrList from './RemarkVrList.vue';
import remarkModel from '@/config/model/remark.json';
import { random } from '@/utils/utilsNew';
import { uploadOSS } from '@/utils/upload';
import { base64ToBlob } from '@/utils';
import { getServerTime } from '@/utils/serverTime';
import { getRequestData, submitXflfpHouse } from '@/api/remark';

export default {
  name: 'RemarkDetailInfoPop',
  components: {
    RemarkVrList,
    RemarkHouseItem,
    RemarkClockIn
  },
  props: {
    item: Object,
    id: String
  },
  data({ item, id }) {
    return {
      vrUrl: '',
      isShowVrDialog: false,
      loading: false,
      isShowClockInBtn: true,
      isClockInLoading: false,
      isShowSelectDialog: false,
      model: {
        houseId: item.id,
        commentContent: '',
        imgUrlList: [],
        reviewDate: '',
        houseType: item.houseType,
        userPortId: id
      },
      uploadList: [],
      isShowPreviewDialog: false,
      previewImageUrl: '',
      clockInStatus: '0', // 0 尚未打卡 1 打卡成功 2 打卡失败 3 自动打卡成功
      clockInErrorMsg: '',
      isShowClockIn: false,
      clockInData: {}, //签到数据
      pickerOptions: {},
      requestId: '' //打卡请求id
    };
  },
  beforeCreate() {},
  created() {
    this.handleRefresh();

    getServerTime().then((t) => {
      this.model.reviewDate = t;
      this.pickerOptions = {
        disabledDate: (time) => {
          let selectTime = time.getTime();
          let rangeTime = 15 * 24 * 3600 * 1000;
          return selectTime < t - rangeTime || selectTime > t;
        }
      };
    });
  },
  mounted() {
    window.addEventListener('message', this.handleMessage);
    this.$once('hook:beforeDestroy', () => window.removeEventListener('message', this.handleMessage));
    this.autoClockIn();
  },
  watch: {
    uploadList(value) {
      this.model.imgUrlList = value.map((v) => v.url);
    }
  },
  computed: {},
  methods: {
    // ------------------handle------------------
    // 弹出vr截图
    async handleTakePhoto(e) {
      try {
        let res;
        if (e.type === 'id') {
          res = await this.$api.getHouseVRUrl({
            delId: e.data
          });
        }
        if (e.type === 'url') {
          res = { isSuccess: true, successMessage: e.data };
        }
        if (res && res.isSuccess) {
          this.vrUrl = `${res.successMessage}&access=screenshot&t=${new Date().getTime()}`;
          this.isShowVrDialog = true;
          this.isShowSelectDialog = false;
        }
      } catch (error) {
        console.log('error', error);
      }
    },
    handleShowClickIn() {
      const { item } = this;
      this.clockInData = {
        houseId: item.id,
        address: `${item.city}-${item.displayDescription}-${item.communityName}`,
        portUserId: item.portUserId
      };
      this.isShowClockIn = true;
    },
    handleUploadPreview(file) {
      this.previewImageUrl = file.url;
      this.isShowPreviewDialog = true;
    },
    handleUploadRemove(file) {
      let indexOfitem = this.uploadList.indexOf(file);
      this.uploadList.splice(indexOfitem, 1);
    },
    handleUploadBefore(file) {
      if (this.checkUploadListNum()) {
        this.uploadImg(file, { isHideSuccessTip: true });
      }
      return false;
    },
    handleUploadExceed() {
      this.$message.info('最多上传9张图片');
    },
    // 上传vr截图
    handleMessage(e) {
      if (!(e && e.origin && /shulanfd\.com|127\.0\.0\.1/.test(e.origin))) {
        return;
      }
      if (e && e.data && e.data.data && e.data.data.img) {
        if (this.checkUploadListNum()) {
          let blob = base64ToBlob(e.data.data.img);
          this.uploadImg(blob);
        }
      }
    },
    // 打卡状态改变
    handleRemarkChange(requestId) {
      if (!requestId) {
        return;
      }
      this.requestId = requestId;
      getRequestData({ requestId }).then(({ status, message }) => {
        this.clockInStatus = status;
        this.clockInErrorMsg = message || '打卡异常';
      });
    },
    // 刷新房评内容
    handleRefresh() {
      let { displayTitle, displayDescription } = this.item;
      let title = `${displayDescription} ${displayTitle}，`;
      this.model.commentContent = title + remarkModel[random(remarkModel.length - 1)];
    },
    // 弹出幸福里vr
    handleCrawlXflVr() {
      this.handleTakePhoto({ type: 'url', data: this.item.vrUrl });
    },
    // ------------------function------------------
    // 提交房评
    submit() {
      const { clockInStatus, requestId, model } = this;
      const { haveAuditSuccess } = this.item;
      if (!(['1', '3'].indexOf(clockInStatus) !== -1)) {
        return this.$message.error('打卡失败，请重新打卡！');
      }
      if (!haveAuditSuccess && model.imgUrlList.length < 2) {
        return this.$message.error('请上传至少两张图片！');
      }
      if (!model.commentContent) {
        return this.$message.error('房评内容不能为空！');
      }
      this.loading = true;
      submitXflfpHouse({
        ...model,
        reviewDate: model.reviewDate / 1000,
        requestId
      })
        .then((content, successMessage) => {
          this.$message.success(successMessage || '房评提交成功');
          this.$emit('portChange');
          this.$emit('close');
        })
        .catch(({ errorMessage, errorCode }) => {
          if (errorCode == 400001) {
            this.isShowClockInBtn = true;
            this.clockInStatus = '2';
          }
          if (errorCode == 400002) {
            this.isShowClockInBtn = true;
            this.clockInStatus = '2';
            this.clockInErrorMsg = errorMessage;
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 上传图片
    async uploadImg(file, options = {}) {
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      try {
        let res = await uploadOSS({
          file,
          rules: [
            { validator: 'type', message: '图片格式只能为jpg/jpeg/png', options: { types: ['jpg', 'jpeg', 'png'] } },
            { validator: 'size', message: '图片大小不能超过2MB', options: { max: 5 } }
          ],
          compressOptions: {}
        });
        if (this.checkUploadListNum()) {
          this.uploadList.push({ name: res.data.name, url: res.data.url });
          if (!options.isHideSuccessTip) {
            this.$message.success('上传成功');
          }
        }
      } catch (error) {
        if ([602, 603].indexOf(error.code) !== -1) {
          this.$message.error(error.msg);
        } else {
          this.$message.error('上传失败');
        }
      } finally {
        loading.close();
      }
    },
    async autoClockIn() {
      try {
        this.isClockInLoading = true;
        const { houseId, houseType } = this.model;
        const { portUserId, city, displayDescription, communityName, coord } = this.item;
        const res = await this.$api.autoClockCheck({
          houseId,
          portUserId,
          houseType,
          address: `${city}${displayDescription}${communityName}`,
          ...coord
        });
        if (res && res.isSuccess) {
          this.requestId = res.content;
          this.clockInStatus = '3';
          this.isShowClockInBtn = false;
        }
      } catch (error) {
        console.log('error', error);
      } finally {
        this.isClockInLoading = false;
      }
    },
    checkUploadListNum() {
      if (this.uploadList && this.uploadList.length >= 9) {
        this.$message.info('最多上传9张图片');
        return false;
      } else {
        return true;
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.refresh {
  position: absolute;
  left: 10px;
  bottom: 0;
}

.dialog-radius /deep/ .el-dialog {
  border-radius: 16px;
}

.vr {
  width: 100%;
  height: 480px;
}
</style>
